package com.mgg.payment.consumer;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

import com.mgg.common.client.message.MessageClient;
import com.mgg.common.consumer.MessageConsumer;
import com.mgg.common.enums.TransferStatusEnum;
import com.mgg.common.exception.ServiceException;
import com.mgg.common.messaging.WithdrawalsProcessor;
import com.mgg.common.payload.WithdrawalsPayload;
import com.mgg.common.util.JsonUtils;
import com.mgg.payment.enums.PaymentResultEnum;
import com.mgg.payment.service.account.AccountService;
import com.mgg.payment.service.alipay.AliPayService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;

@Component
public class WithdrawalsMessageConsumer implements MessageConsumer<WithdrawalsPayload> {

	Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
    private AliPayService aliPayService;
	
	@Autowired
    private AccountService accountService;
	
	@Autowired
    private MessageClient messageClient;
	
	@Autowired
    @Qualifier("poolTaskExecutor")
    private Executor executor;
	
    @StreamListener(WithdrawalsProcessor.INPUT)
    @Transactional
	@Override
	public void receiveMessage(WithdrawalsPayload payload) {
    	log.info("MQ【支付宝提现】，payload = {}", JsonUtils.toJson(payload));
    	String transferNo = payload.getTransferNo();
    	try {
    		//1. 查询订单
            Map<String,String> transferMap = accountService.getTransferByNo(transferNo,"2","1");
            if (MapUtils.isEmpty(transferMap)) {
                throw new ServiceException(PaymentResultEnum.TRANSFER_NOT_FIND_ERROR.getCode(), PaymentResultEnum.TRANSFER_NOT_FIND_ERROR.getMessage());
            }
            
    		AlipayFundTransToaccountTransferResponse response = aliPayService.transfer(transferMap);
    		
    		String orderNo = response.getOrderId();
    		String payTime = response.getPayDate();
    		if(response.isSuccess()){
    			accountService.updateTransfer(transferNo, orderNo, payTime, payTime, TransferStatusEnum.CWD_ING.getCode(), null);
    			log.info("【支付宝提现】, 转账成功, 网关返回码={}, 网关返回码描述={}, 业务返回码={}, 业务返回码描述={}, transfer_no={}", 
    					response.getSubCode(), response.getSubMsg(), response.getCode(), response.getMsg(), transferMap.get("transfer_no"));
    		} else {
    			String reason = response.getSubMsg();
    			String userId = transferMap.get("user_id");
    			accountService.updateTransfer(transferNo, orderNo, payTime, payTime, TransferStatusEnum.CWD_FAIL.getCode(),
    					"转账失败, 网关返回码=" + response.getSubCode() +", 网关返回码描述=" + reason);
    			accountService.updateAccount(userId, null, new BigDecimal(transferMap.get("amount")), null, 8, transferNo, "提现失败，余额退回");
    			log.error("【支付宝提现】, 转账失败, 网关返回码={}, 网关返回码描述={}, 业务返回码={}, 业务返回码描述={}, transfer_no={}", 
    					response.getSubCode(), response.getSubMsg(), response.getCode(), response.getMsg(), transferMap.get("transfer_no"));
    			
    			//发送短信
    			CompletableFuture
    			.runAsync(() -> {
    				String createTime = transferMap.get("create_time");
    				DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    				LocalDateTime dateTime = LocalDateTime.parse(createTime, df);
    				String date = dateTime.getMonthValue() + "月" + dateTime.getDayOfMonth() + "日";
					messageClient.sendWithdrawFail(userId,date,reason);
    			}, executor);
        	}
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			log.error("【支付宝提现】，transferNo = {}", transferNo);
		}
	}
}
